const Koa = require('koa2'),
	Router = require('koa-router'),
	cheerio = require('cheerio'),
	path = require('path'),
	superagent = require('superagent');
const fs = require("fs");

require('superagent-charset')(superagent);

const app = new Koa(),
	  router = new Router();

const getPage = (url) => {
	return new Promise((ok,fail) => {
		superagent.get(url).charset('utf-8').buffer(true).then(sres => {
			if (sres){
				// ok(sres.text)
				const $ = cheerio.load(sres.text, {
					decodeEntities: false
				});
				const charset = ($('head meta[http-equiv="Content-Type"]')[0].attribs.content);
				console.log(sres.text)
				ok('ok')
			}
		}).catch((err) => {
			ok('in err ' + JSON.stringify(err));
			if (err) {
				console.log('catch err')
			}
		});
	});
}

router.get('/:url', async (ctx, next) => {
	const {
		url,
	} = ctx.params;
	ctx.body = await getPage(url);
})

app.use(router.routes()).use(router.allowedMethods());

app.listen(3000, () => {
	console.log('[服务已开启,访问地址为：] http://127.0.0.1:3000/');
});
